// pages/shop/shop.js
import { getShop } from "../../server/shop"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    option1: [
      { text: '默认排序', value: "defalut" },
      { text: '按价格排序', value: "price" },
      { text: '按评论数排序', value: "comments_count" },
      { text: '按销量排序', value: "sales" },
    ],
    value1: "defalut",
    page: 1,
    categories: [],
    goods: [],
    itemTitle: '筛选',
    mainActiveIndex: 0,
    activeId: null,
    isLast: false,
    loading: false,
    valueSearch: ""
  },
  /**
 * 生命周期函数--监听页面加载
 */
  onLoad: function (options) {
    this.OnGetShop()
  },
  OnGetShop() {
    this.setData({
      loading: true
    })
    let { value1, page, valueSearch ,activeId} = this.data
    let data = {
      page: page,
      title: valueSearch
    }
    if (value1 !== "defalut") data[value1] = 1

    if(activeId) data.category_id = activeId
    console.log(data);
    getShop(data).then(res => {
      this.setData({
        loading: false
      })
      // console.log(res);
      this.setData({
        goods: [...this.data.goods, ...res.goods.data],
        categories: JSON.parse(JSON.stringify(res.categories).replace(/name/gi, "text")),
        isLast: res.goods.data.length < 10 ? true : false
      })
      // console.log(this.data.goods);
      // console.log(this.data.categories);
      // console.log(this.data.goods);
    })
    // console.log(items1);
    // console.log(res.categories);

  },
  onSearchChange({ detail = {} }) {
    this.setData({
      valueSearch: detail
    })
    // console.log(this.data.value);
  },
  onValue1Change(e) {
    console.log(e.detail);
    this.setData({
      value1: e.detail,
      goods: []
    })
    this.OnGetShop()
  },
  onClickSearch() {
    this.setData({
      goods: []
    })
    this.OnGetShop()
  },
  onClickNav({ detail = {} }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
  },
  onClickItem({ detail = {} }) {
    const activeId = this.data.activeId === detail.id ? null : detail.id;
    this.setData({
      activeId,
      goods:[],
      itemTitle:activeId?detail.text:"筛选"
    });
    this.selectComponent('#item').toggle();
    this.OnGetShop()
  },
  /**
  * 页面上拉触底事件的处理函数
  */
  onReachBottom: function () {
    if (!this.data.isLast) {
      this.setData({
        page: this.data.page + 1
      })
      this.OnGetShop()
    }
  },
})

